//
//  ZSUDPServer.m
//  ZhuShou
//
//  Created by Dejun Liu on 15/11/9.
//  Copyright © 2015年 jw. All rights reserved.
//

#import "ZSUDPServer.h"

@implementation ZSUDPServer

- (void)startUDPServer:(BOOL) shouldStart port:(NSInteger) port
{
    if (shouldStart) {
        if (!_server) {
            _server = [[GCDAsyncUdpSocket alloc] initWithDelegate:self
                                                            delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
        }
        
        if (port < 0 || port > 65535)
        {
            port = 0;
        }
        
        NSError *error = nil;
        
        BOOL success = [_server bindToPort:port error:&error];
        if (!success)
        {
            DLog(@"Error starting server (bind): %@", error);
            return;
        }

        if (![_server beginReceiving:&error])
        {
            [_server close];
            
            DLog(@"Error starting server (recv): %@", error);
            return;
        }
        
        DLog(@"Udp Echo server started on port %hu", [_server localPort]);
        
        NSError *broadcastError;
        [_server enableBroadcast:YES error:&broadcastError];
        
        _isRunning = YES;
    }else
    {
        [self stopServer];
    }
}

- (void)stopServer
{
    [_server close];
    DLog(@"Stopped Udp Echo server");
    _server = false;
}

#pragma mark 发送消息

- (void)sendString:(NSString *)string
            hostIP:(NSString *) ip
              port:(UInt16) port
           timeout:(NSTimeInterval) timeout
               tag:(long) tag
{
    [self sendData:[string dataUsingEncoding:NSUTF8StringEncoding] hostIP:ip port:port timeout:timeout tag:tag];
}

- (void)sendData:(NSData *)data
          hostIP:(NSString *) ip
            port:(UInt16) port
         timeout:(NSTimeInterval) timeout
             tag:(long) tag
{
    if (!_server) {
        _server = [[GCDAsyncUdpSocket alloc] initWithDelegate:self
                                                delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    }
    [_server sendData:data toHost:ip port:port withTimeout:timeout tag:tag];
}

#pragma mark AsyncUdpSocketDelegate

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address
{
    DLog(@"didConnectToAddress");
    if (_eventCallBack) {
        _eventCallBack(UDPServerEventTypeDidConnectToAddress,sock,address,nil,nil,nil,-1,nil);
    }
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError *)error
{
    DLog(@"didNotConnect");
    if (_eventCallBack) {
        _eventCallBack(UDPServerEventTypeDidNotConnect,sock,nil,nil,nil,error,-1,nil);
    }
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
    DLog(@"didSendDataWithTag");
    if (_eventCallBack) {
        _eventCallBack(UDPServerEventTypeDidSendData,sock,nil,nil,nil,nil,tag,nil);
    }
    
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
    DLog(@"didNotSendDataWithTag");
    if (_eventCallBack) {
        _eventCallBack(UDPServerEventTypeDidNotSendData,sock,nil,nil,nil,error,tag,nil);
    }
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
      fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
    DLog(@"didReceiveData");
    if (_eventCallBack) {
        _eventCallBack(UDPServerEventTypeDidReceiveData,sock,nil,address,data,nil,-1,filterContext);
    }
}

- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error
{
    DLog(@"udpSocketDidClose");
    if (_eventCallBack) {
        _eventCallBack(UDPServerEventTypeDidClose,sock,nil,nil,nil,error,-1,nil);
    }
}

@end
